//
//  PhotoTools.swift
//  MintBag
//
//  Created by 魏延(颜魏) on 2024/10/17.
//

import UIKit

class PhotoTools: NSObject {
    static let shared = PhotoTools()
    var complation: ((UIImage)->Void)?

    func selectPhoto(_ isFront: Bool, vc: UIViewController, complate:@escaping (UIImage)->Void) {
        complation = complate
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let imagePicker = UIImagePickerController()
            imagePicker.sourceType = .camera
            imagePicker.delegate = self
            imagePicker.cameraDevice = isFront ? .front : .rear
            vc.present(imagePicker, animated: true, completion: nil)
        }
    }
}

extension PhotoTools: UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    // 获取拍摄的照片
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[.originalImage] as? UIImage, let img = resizeImage(image: image, targetWidth: Const.windowWidth) {
            complation?(img)
            complation = nil
        }
        picker.dismiss(animated: true, completion: nil)
    }

    // 用户取消拍照
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func resizeImage(image: UIImage, targetWidth: CGFloat) -> UIImage? {
        // 获取原图的尺寸
        let originalWidth = image.size.width
        let originalHeight = image.size.height
        
        // 计算新的高度，保持宽高比
        let scaleFactor = targetWidth / originalWidth
        let targetHeight = originalHeight * scaleFactor
        
        // 创建绘图上下文，绘制缩放后的图像
        let newSize = CGSize(width: targetWidth, height: targetHeight)
        let renderer = UIGraphicsImageRenderer(size: newSize)
        
        let resizedImage = renderer.image { (context) in
            image.draw(in: CGRect(origin: .zero, size: newSize))
        }
        
        return resizedImage
    }

}
